package com.mycompany.client;

import java.util.LinkedHashMap;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.HistoryListener;
import com.google.gwt.user.client.ui.RootPanel;
import com.mycompany.client.i18n.Context;
import com.mycompany.shared.EnvConstants;
import com.smartgwt.client.core.KeyIdentifier;
import com.smartgwt.client.types.DateDisplayFormat;
import com.smartgwt.client.types.TabBarControls;
import com.smartgwt.client.util.DateUtil;
import com.smartgwt.client.util.I18nUtil;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.ImgButton;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ShowContextMenuEvent;
import com.smartgwt.client.widgets.events.ShowContextMenuHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.events.ChangeEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangeHandler;
import com.smartgwt.client.widgets.grid.events.CellClickEvent;
import com.smartgwt.client.widgets.grid.events.CellClickHandler;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.Layout;
import com.smartgwt.client.widgets.layout.LayoutSpacer;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.menu.Menu;
import com.smartgwt.client.widgets.menu.MenuBar;
import com.smartgwt.client.widgets.menu.MenuItem;
import com.smartgwt.client.widgets.menu.MenuItemIfFunction;
import com.smartgwt.client.widgets.menu.events.ClickHandler;
import com.smartgwt.client.widgets.menu.events.MenuItemClickEvent;
import com.smartgwt.client.widgets.tab.Tab;
import com.smartgwt.client.widgets.tab.TabSet;
import com.smartgwt.client.widgets.tab.events.TabSelectedEvent;
import com.smartgwt.client.widgets.tab.events.TabSelectedHandler;
import com.smartgwt.client.widgets.toolbar.ToolStrip;
import com.smartgwt.client.widgets.toolbar.ToolStripButton;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Helloworld implements EntryPoint, HistoryListener {

	private SideNavGrid featureTree;
	private TabSet mainTabSet;
	
	public void onModuleLoad() {
		I18nUtil.init();
//		DateUtil.setNormalDateDisplayFormat(DateDisplayFormat.TOSERIALIZEABLEDATE);
		final String initToken = History.getToken();

		// setup overall layout / viewport
		VLayout main = new VLayout() {
			@Override
			protected void onInit() {
				super.onInit();
				if (initToken.length() != 0) {
					onHistoryChanged(initToken);
				}
			}
		};

		ToolStrip topBar = new ToolStrip();
		topBar.setHeight(33);
		topBar.setWidth100();

		topBar.addSpacer(6);
		ImgButton sgwtHomeButton = new ImgButton();
		sgwtHomeButton.setSrc("pieces/24/cube_green.png");
		sgwtHomeButton.setWidth(24);
		sgwtHomeButton.setHeight(24);
		sgwtHomeButton.setPrompt("Smart GWT Project Page");
		sgwtHomeButton.setHoverStyle("interactImageHover");
		sgwtHomeButton.setShowRollOver(false);
		sgwtHomeButton.setShowDownIcon(false);
		sgwtHomeButton.setShowDown(false);
		sgwtHomeButton
				.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() {
					public void onClick(ClickEvent event) {
						com.google.gwt.user.client.Window.open(
								"http://code.google.com/p/smartgwt/", "sgwt",
								null);
					}
				});
		topBar.addMember(sgwtHomeButton);
		topBar.addSpacer(6);

		Label title = new Label(Context.i18N().helloWorld());
		title.setStyleName("sgwtTitle");
		title.setWidth(300);
		topBar.addMember(title);
		topBar.addFill();

		ToolStripButton welcomeButton = new ToolStripButton() {{
			setTitle("Welcome Coral!");
			addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() {
						public void onClick(ClickEvent event) {
							SC.say("Welcome Coral!");
						}
					});
		}};
		topBar.addButton(welcomeButton);
		topBar.addSeparator();
		
		ToolStripButton emailButton = new ToolStripButton() {{
			setTitle("Email");
			addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() {
						public void onClick(ClickEvent event) {
							SC.say("Email");
						}
					});
		}};
		topBar.addButton(emailButton);
		topBar.addSeparator();
		

		ToolStripButton settingButton = new ToolStripButton() {{
			setTitle("Settings");
			addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() {
						public void onClick(ClickEvent event) {
							SC.say("Settings");
						}
					});
		}};
		topBar.addButton(settingButton);
		topBar.addSeparator();
		
		ToolStripButton helpButton = new ToolStripButton() {{
			setTitle("Help");
			addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() {
						public void onClick(ClickEvent event) {
							SC.say("Help");
						}
					});
		}};
		topBar.addButton(helpButton);
		topBar.addSeparator();
		
		ToolStripButton logoutButton = new ToolStripButton() {{
			setTitle("Logout");
			addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() {
						public void onClick(ClickEvent event) {
							SC.say("Logout");
						}
					});
		}};
		topBar.addButton(logoutButton);
//		ImgButton imgButton = new ImgButton();
//		imgButton.setWidth(18);
//		imgButton.setHeight(18);
//		imgButton.setSrc("silk/emoticon.png");
//		imgButton.setShowFocused(false);
//		imgButton.setShowFocusedIcon(false);
//		imgButton.setPrompt("I'm feeling lucky");
//		imgButton.setHoverWidth(110);
//		imgButton.setHoverStyle("interactImageHover");
//
//		
//		topBar.addMember(imgButton);
		topBar.addSpacer(6);
		main.addMember(topBar);
		
//		MainMenu m = new MainMenu();
//		MenuBar menubar = m.getMenu();
//		ToolStrip toolMenuBar = new ToolStrip();
//		toolMenuBar.setHeight(menubar.getHeight());
//		toolMenuBar.setWidth100();
//		toolMenuBar.addMember(menubar);
//		main.addMember(toolMenuBar);
		
		main.setWidth100();
		main.setHeight100();
		main.setStyleName("tabSetContainer");

		HLayout hLayout = new HLayout();
		hLayout.setWidth100();
		hLayout.setHeight100();

		VLayout sideNavLayout = new VLayout();
		sideNavLayout.setHeight100();
		sideNavLayout.setWidth(EnvConstants.SIDE_NAVIGATION_BAR_LENGTH);
		sideNavLayout.setShowResizeBar(true);

		featureTree = new SideNavGrid();
		featureTree.addCellClickHandler(new CellClickHandler() {
			
			public void onCellClick(CellClickEvent event) {
				String pageID = event.getRecord().getAttribute("page");
				if(pageID != null) {
//					pageController(pageID);
					PageFlowController.pageController(pageID);
				}
			}
		});
		sideNavLayout.addMember(featureTree);
		hLayout.addMember(sideNavLayout);

		mainTabSet = new TabSet();
		Layout paneContainerProperties = new Layout();
		paneContainerProperties.setLayoutMargin(0);
		paneContainerProperties.setLayoutTopMargin(1);
		mainTabSet.setPaneContainerProperties(paneContainerProperties);

		mainTabSet.setWidth100();
		mainTabSet.setHeight100();
		mainTabSet.addTabSelectedHandler(new TabSelectedHandler() {
			public void onTabSelected(TabSelectedEvent event) {
				Tab selectedTab = event.getTab();
				String historyToken = selectedTab.getAttribute("historyToken");
				if (historyToken != null) {
					History.newItem(historyToken, false);
				} else {
					History.newItem("main", false);
				}
			}
		});

		LayoutSpacer layoutSpacer = new LayoutSpacer();
		layoutSpacer.setWidth(5);

		SelectItem selectItem = new SelectItem();
		selectItem.setHeight(21);
		selectItem.setWidth(130);
		LinkedHashMap<String, String> valueMap = new LinkedHashMap<String, String>();
		valueMap.put("EnterpriseBlue", "Enterprise Blue");
		valueMap.put("Enterprise", "Enterprise Gray");
		valueMap.put("Graphite", "Graphite");

		selectItem.setValueMap(valueMap);

		String currentSkin = Cookies.getCookie("skin_name");
		if (currentSkin == null) {
			currentSkin = "EnterpriseBlue";
		}
		selectItem.setDefaultValue(currentSkin);
		selectItem.setShowTitle(false);
		selectItem.addChangeHandler(new ChangeHandler() {
			public void onChange(ChangeEvent event) {
				Cookies.setCookie("skin_name", (String) event.getValue());
				com.google.gwt.user.client.Window.Location.reload();
			}
		});

		DynamicForm form = new DynamicForm();
		form.setPadding(0);
		form.setMargin(0);
		form.setCellPadding(1);
		form.setNumCols(1);
		form.setFields(selectItem);

		mainTabSet.setTabBarControls(TabBarControls.TAB_SCROLLER,
				TabBarControls.TAB_PICKER, layoutSpacer, form);

		final Menu contextMenu = createContextMenu();
		mainTabSet.addShowContextMenuHandler(new ShowContextMenuHandler() {
			public void onShowContextMenu(ShowContextMenuEvent event) {
				int selectedTab = mainTabSet.getSelectedTabNumber();
				if (selectedTab != 0) {
					contextMenu.showContextMenu();
				}
				event.cancel();
			}
		});

//		Tab tab = new Tab();
//		tab.setTitle("Home&nbsp;&nbsp;");
//		tab.setIcon("pieces/16/cube_green.png");
//		tab.setWidth(80);
//		CoralHLayout100 mainPanel = new CoralHLayout100();
//        CalendarPage calendarPage = new CalendarPage();
//        Calendar calendar = calendarPage.getCalendar();
//	    mainPanel.addMember(calendar);
//		tab.setPane(mainPanel);
//		mainTabSet.addTab(tab);
		
//		Tab saTab = new Tab();
//		saTab.setTitle("Add Sales Activity&nbsp;&nbsp;");
//		saTab.setIcon("pieces/16/cube_green.png");
//		saTab.setWidth(80);
//		CoralHLayout100 saPanel = new CoralHLayout100();
//        AddSalesActivityPage saPage = new AddSalesActivityPage();
//        saPanel.addMember(saPage.getViewPage());
//	    saTab.setPane(saPanel);
//	    mainTabSet.addTab(saTab);
	    
//	    Tab msaTab = new Tab();
//		msaTab.setTitle("Sales Activity&nbsp;&nbsp;");
//		msaTab.setIcon("pieces/16/cube_green.png");
//		msaTab.setWidth(80);
//		CoralHLayout100 msaPanel = new CoralHLayout100();
//		ManageSalesActivityPage msaPage = new ManageSalesActivityPage();
//        msaPanel.addMember(msaPage.getViewPage());
//	    msaTab.setPane(msaPanel);
//	    mainTabSet.addTab(msaTab);

	    
	    
		Canvas canvas = new Canvas();
		canvas.setBackgroundImage("[SKIN]/shared/background.gif");
		canvas.setWidth100();
		canvas.setHeight100();
		canvas.addChild(mainTabSet);

		hLayout.addMember(canvas);
		main.addMember(hLayout);
		main.draw();

		// Add history listener
		History.addHistoryListener(this);
		PageFlowController.setMainTabSet(mainTabSet);

		RootPanel.getBodyElement().removeChild(
				RootPanel.get("loadingWrapper").getElement());
	}

	private Menu createContextMenu() {
		Menu menu = new Menu();
		menu.setWidth(140);

		MenuItemIfFunction enableCondition = new MenuItemIfFunction() {
			public boolean execute(Canvas target, Menu menu, MenuItem item) {
				int selectedTab = mainTabSet.getSelectedTabNumber();
				return selectedTab != 0;
			}
		};

		MenuItem closeItem = new MenuItem("<u>C</u>lose");
		closeItem.setEnableIfCondition(enableCondition);
		closeItem.setKeyTitle("Alt+C");
		KeyIdentifier closeKey = new KeyIdentifier();
		closeKey.setAltKey(true);
		closeKey.setKeyName("C");
		closeItem.setKeys(closeKey);
		closeItem.addClickHandler(new ClickHandler() {
			public void onClick(MenuItemClickEvent event) {
				int selectedTab = mainTabSet.getSelectedTabNumber();
				mainTabSet.removeTab(selectedTab);
				mainTabSet.selectTab(selectedTab - 1);
			}
		});

		MenuItem closeAllButCurrent = new MenuItem("Close All But Current");
		closeAllButCurrent.setEnableIfCondition(enableCondition);
		closeAllButCurrent.addClickHandler(new ClickHandler() {
			public void onClick(MenuItemClickEvent event) {
				int selected = mainTabSet.getSelectedTabNumber();
				Tab[] tabs = mainTabSet.getTabs();
				int[] tabsToRemove = new int[tabs.length - 2];
				int cnt = 0;
				for (int i = 1; i < tabs.length; i++) {
					if (i != selected) {
						tabsToRemove[cnt] = i;
						cnt++;
					}
				}
				mainTabSet.removeTabs(tabsToRemove);
			}
		});

		MenuItem closeAll = new MenuItem("Close All");
		closeAll.setEnableIfCondition(enableCondition);
		closeAll.addClickHandler(new ClickHandler() {
			public void onClick(MenuItemClickEvent event) {
				Tab[] tabs = mainTabSet.getTabs();
				int[] tabsToRemove = new int[tabs.length - 1];

				for (int i = 1; i < tabs.length; i++) {
					tabsToRemove[i - 1] = i;
				}
				mainTabSet.removeTabs(tabsToRemove);
				mainTabSet.selectTab(0);
			}
		});

		menu.setItems(closeItem, closeAllButCurrent, closeAll);
		return menu;
	}

	@Deprecated
	public void pageController(String pageID) {
		Tab tab = null;
		if (pageID != null) {
            String tabID = pageID + "_tab";
            tab = mainTabSet.getTab(tabID);
        }
		if (tab == null) {
			CoralPage page = CoralPageFactory.getPanel(pageID);
			if(page == null) {
				return;
			}
			tab = new Tab();
            tab.setID(pageID + "_tab");
            tab.setAttribute("historyToken", pageID);
            
            String pageName = page.getPageName();
            String icon = page.getIcon();
            if (icon == null) {
                icon = "silk/plugin.png";
            }
            String imgHTML = Canvas.imgHTML(icon, 16, 16);
            tab.setTitle("<span>" + imgHTML + "&nbsp;" + pageName + "&nbsp;&nbsp;</span>");
            tab.setPane(page.getViewPage());
            
            if(EnvConstants.SINGLE_PAGE) {
            	tab.setCanClose(false);
            	int index = mainTabSet.getTabs().length;
            	if(index > 0) {
            		mainTabSet.removeTab(0);
            	}
    		} else {
	            tab.setCanClose(true);
    		}
            mainTabSet.addTab(tab);
            mainTabSet.selectTab(tab);
		} else {
            mainTabSet.selectTab(tab);
		}
		History.newItem(pageID, false);
	}

	public void onHistoryChanged(String historyToken) {
		if (historyToken == null || historyToken.equals("")) {
			mainTabSet.selectTab(0);
		}
	}
}